using System;
using System.Collections.Generic;
using FireStarter.CodeGeneration.Generator;

namespace FireStarter.CodeGeneration.Parser
{
    public class ExpressionParser : ParserBase
    {
        public override TemplateExpression Parse(ref string templateText, List<IActionParser> actionParsers)
        {
            string expressionText = GetAndConsumeExpressionText(ref templateText);
            if (string.IsNullOrEmpty(expressionText)) return new LiteralExpression(expressionText);
            foreach (IActionParser actionParser in actionParsers)
            {
                if (actionParser.IsExpressionMatch(expressionText))
                {
                    return actionParser.Parse(ref expressionText, actionParsers);
                }
            }
            throw new ParserException(string.Format("The given action does not match the template language: {0}" +
                Environment.NewLine + "(Note that a value replacement is preceded by = )", 
                expressionText));
        }

        private string GetAndConsumeExpressionText(ref string templateText)
        {
            templateText = templateText.Remove(0, START_TAG.Length);
            int endTagPos = ParserUtilities.IndexOfCorrespondingEndTag(START_TAG, END_TAG, templateText);

            if (endTagPos < 0)
            {
                int lengthToShow = templateText.Length;
                if (lengthToShow > 30) lengthToShow = 30; //makes the error message readable
                throw new ParserException("A template had no closing tag: " + templateText.Substring(0, lengthToShow));
            }
            string expressionText = templateText.Substring(0, endTagPos).TrimStart();
            templateText = templateText.Remove(0, endTagPos + END_TAG.Length);
            return expressionText;
        }
    }
}